package aleksandar.djuric.gui;

import javax.swing.JPanel;
import java.awt.Frame;
import java.awt.Image;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JWindow;



public class Waiter extends JWindow implements ComponentListener{

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private Image waitImage = null;
	private Waiter waiter = this;
	private boolean work = true;

	/**
	 * @param owner
	 */
	public Waiter(Frame owner) {
		super(owner);
		waitImage = MainFrame.mainFrame.waiters[0];
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(48, 48);
		this.setContentPane(getJContentPane());
		this.addComponentListener(this);
		this.setEnabled(false);
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel()
			{
				private static final long serialVersionUID = 1L;

				public void paint(java.awt.Graphics g) 
				{
					g.drawImage(waitImage, 0, 0, null);
				};
			};
		}
		return jContentPane;
	}
	
	private class ImageChanger extends Thread
	{
		@Override
		public void run() {
			try 
			{
				while(work)
				{
					Image[] waiters = MainFrame.mainFrame.waiters;
					for (int i = 0; i < waiters.length; i++) 
					{
						waitImage = waiters[i];
						waiter.repaint();
						sleep(100);
						if(work == false)
							break;
					}
				}
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
	}

	@Override
	public void componentHidden(ComponentEvent e) {
		work = false;
	}

	@Override
	public void componentMoved(ComponentEvent e) {
		
	}

	@Override
	public void componentResized(ComponentEvent e) {
		
	}

	@Override
	public void componentShown(ComponentEvent e) {
		int x = getOwner().getX();
		int y = getOwner().getY();
		int width = getOwner().getWidth();
		int height = getOwner().getHeight();
		this.setLocation(x + width / 2 - getWidth() / 2,
						 y + height / 2 - getHeight() / 2);
		work = true;
		ImageChanger ic = new ImageChanger();
		ic.start();
	}

}
